<?php


namespace app\cms\model;


use app\cms\community\lib\QueryModel;
use app\cms\dto\formFieldInfo;
use iflow\Response;

class formFieldModel extends QueryModel
{

    protected $table = "form_field_table";

    public function addField(formFieldInfo $formFieldInfo): Response
    {
        return $this -> createData([
            'form_id' => $formFieldInfo -> form_id,
            'form_field_name' => $formFieldInfo -> form_field_name,
            'form_field_as_name' => $formFieldInfo -> form_field_as_name,
            'form_field_type' => $formFieldInfo -> form_field_type,
            'form_field_length' => $formFieldInfo -> form_field_length,
            'form_field_description' => $formFieldInfo -> form_field_description,
            'form_field_default' => $formFieldInfo -> form_field_default
        ]);
    }

    public function getFields(int $form_id, string $form_field_name = ''): Response
    {
        $query = $this -> where([
            'form_id' => $form_id
        ]);
        return $this -> paginates($query, $form_field_name);
    }

    public function getFieldByFormName(string $form_name, string $form_field_name = ''): Response
    {
        $form = (new formModel) -> getFormByFormName($form_name);
        if (!$form) return message() -> update_failed('暂无表单数据');

        $query = $this -> where([
            'form_id' => $form['form_id']
        ]);
        return $this -> paginates($query, $form_field_name);
    }

    private function paginates($query, $form_field_name, int $page = 0): Response
    {
        if ($form_field_name !== '') {
            $query = $query -> whereLike('form_field_name', "%{$form_field_name}%");
        }
        $query = $query -> paginate([
            'page' => $page ?? request() -> getParams('page'),
            'list_rows' => request() -> getParams('rows') ?: 999
        ]);
        return $query -> items() ?
            message() -> success('查询成功', $query -> items(), [
                'count' => $query -> total(),
                'page' => $query -> lastPage()
            ]) : message() -> update_failed('暂无表单数据');
    }
}